package com.yanqu.road.server.manager.activity.liondance;

import com.yanqu.road.dao.impl.activity.liondance.CrossLionDanceAllDataDaoImpl;
import com.yanqu.road.dao.impl.activity.liondance.CrossLionDanceUserProcessDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.liondance.CrossLionDanceAllData;
import com.yanqu.road.entity.activity.liondance.CrossLionDanceUserProcessData;
import com.yanqu.road.entity.activity.liondance.LionDanceUserApplyData;
import com.yanqu.road.pb.activity.LionDanceProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LionDanceActivity {

    private ActivityInfo activityInfo;

    //玩家贡献进度
    Map<Long, CrossLionDanceUserProcessData> userProcessDataMap;

    //全服进度
    CrossLionDanceAllData activityData;

    //玩家申请记录
    Map<Long, LionDanceUserApplyData> applyDataMap;

    public LionDanceActivity(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
    }

    public void init(){
        userProcessDataMap = new CrossLionDanceUserProcessDataDaoImpl().getCrossLionDanceUserProcessData(activityInfo.getActivityId());
        activityData = new CrossLionDanceAllDataDaoImpl().getCrossLionDanceAllData(activityInfo.getActivityId());
        if(activityData == null){
            activityData = new CrossLionDanceAllData();
            activityData.setActivityId(activityInfo.getActivityId());
            activityData.setInsertOption();
        }
        applyDataMap = new ConcurrentHashMap<>();
    }

    public ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public void setActivityInfo(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
    }

    public void save() {
        if(activityData != null){
            if(activityData.isInsertOption()){
                new CrossLionDanceAllDataDaoImpl().add(activityData);
            }else if(activityData.isUpdateOption()){
                new CrossLionDanceAllDataDaoImpl().update(activityData);
            }
        }
        if(userProcessDataMap != null){
            for (Map.Entry<Long, CrossLionDanceUserProcessData> entry : userProcessDataMap.entrySet()) {
                if(entry.getValue().isInsertOption()){
                    new CrossLionDanceUserProcessDataDaoImpl().add(entry.getValue());
                }else if(entry.getValue().isUpdateOption()){
                    new CrossLionDanceUserProcessDataDaoImpl().update(entry.getValue());
                }
            }
        }
    }

    public synchronized void calCrossLionDanceAllData() {
        if(activityData == null || userProcessDataMap == null){
            return;
        }
        if(userProcessDataMap.size() == 0){
            return;
        }
        long count = 0;
        long oldAllProcess = 1000 * activityData.getAllMakeNum() + activityData.getAllProcess();
        long allProcess = 0L;
        for (Map.Entry<Long, CrossLionDanceUserProcessData> entry : userProcessDataMap.entrySet()) {
            count += entry.getValue().getMakeNum();
            allProcess += entry.getValue().getProcess();
        }
        long newProcess = 1000 * count + allProcess;
        long addCount = allProcess / 1000;
        count += addCount;
        if(oldAllProcess != newProcess){
            activityData.setAllMakeNum(count);
            activityData.setAllProcess(allProcess - addCount * 1000);
            activityData.setUpdateTime(System.currentTimeMillis());
            //同步给活动所有区服
            if(activityInfo != null){
                LionDanceProto.CrossLionDanceSyncAllMakeNumMsg.Builder sync = LionDanceProto.CrossLionDanceSyncAllMakeNumMsg.newBuilder();
                sync.setActivityId(activityInfo.getActivityId());
                sync.setCount(count);
                sync.setProcess((int)activityData.getAllProcess());
                for (Long sid : activityInfo.getServerIdList()) {
                    MessageHelper.sendPacket(sid, 0, YanQuMessageUtils.buildMessage(Protocol.S_LION_DANCE_ALL_CONTRIBUTION_SYNC_FROM_CROSS, sync));
                }
            }
        }
    }

    public void updateUserMakeNum(long userId, int num, int process, boolean needSync){
        synchronized (CrossLionDanceActivityMgr.getUserLocker(userId)){
            CrossLionDanceUserProcessData userProcessData = userProcessDataMap.get(userId);
            if(userProcessData == null){
                userProcessData = new CrossLionDanceUserProcessData();
                userProcessData.setInsertOption();
                userProcessData.setActivityId(activityInfo.getActivityId());
                userProcessData.setUserId(userId);
            }
            userProcessData.setMakeNum(num);
            userProcessData.setProcess(process);
            userProcessData.setUpdateTime(System.currentTimeMillis());
            if(userProcessData.isInsertOption()){
                userProcessDataMap.put(userId, userProcessData);
            }
            CrossLionDanceActivityMgr.getLogger().info("-------------- 玩家更新狮头进度 {}：{} ：{}", userProcessData.getUserId(), userProcessData.getMakeNum(), userProcessData.getProcess());
        }
        if(needSync){
            calCrossLionDanceAllData();
        }
    }

    /**
     * 申请集卡协助
     */
    public void applyCard(long playerId, int cardId, long time, int applyNo, long serverId) {
        LionDanceUserApplyData applyData = new LionDanceUserApplyData();
        applyData.setApplyNo(applyNo);
        applyData.setUserId(playerId);
        applyData.setActivityId(activityInfo.getActivityId());
        applyData.setApplyTimes(time);
        applyData.setApplyGoodsId(cardId);
        applyData.setServerId(serverId);
        applyDataMap.put(playerId, applyData);
    }

    /**
     * 取消集卡协助
     */
    public void cancelApplyCard(long playerId, int applyNo) {
        LionDanceUserApplyData applyData = applyDataMap.get(playerId);
        if(applyData != null && applyData.getApplyNo() == applyNo){
            applyData.setStatus(4);
            applyDataMap.remove(playerId);
        }
    }

    /**
     * 赠送
     */
    public void giveGift(LionDanceProto.CrossLionDanceApplyHandleReqMsg reqMsg){
        LionDanceUserApplyData applyData = applyDataMap.remove(reqMsg.getToUserId());
        if(applyData == null || applyData.getStatus() != 0 || applyData.getApplyNo() != reqMsg.getApplyNo() || applyData.getApplyGoodsId() != reqMsg.getCardId()){

            LionDanceProto.CrossLionDanceApplyHandleRespMsg.Builder resp = builderHandleResp(-1, reqMsg.getFromUserId(), reqMsg.getFromServerId(), reqMsg.getToUserId(), reqMsg.getApplyNo(), reqMsg.getCardId());
            resp.setActivityId(activityInfo.getActivityId());
            MessageHelper.sendPacket(reqMsg.getFromServerId(), reqMsg.getFromUserId(),
                    YanQuMessageUtils.buildMessage(Protocol.S_LION_DANCE_GIVE_FRIEND_BACK_FROM_CROSS,
                            resp));
            return;
        }

        MessageHelper.sendPacket(reqMsg.getToServerId(), reqMsg.getToUserId(), YanQuMessageUtils.buildMessage(Protocol.S_LION_DANCE_GIVE_FRIEND_FROM_CROSS, reqMsg));
    }


    public static LionDanceProto.CrossLionDanceApplyHandleRespMsg.Builder builderHandleResp(int ret, long fromUserId, long fromServerId, long toUserId, int applyNo, int cardId){
        LionDanceProto.CrossLionDanceApplyHandleRespMsg.Builder builder = LionDanceProto.CrossLionDanceApplyHandleRespMsg.newBuilder();
        builder.setRet(ret);
        builder.setApplyNo(applyNo);
        builder.setCardId(cardId);
        builder.setFromUserId(fromUserId);
        builder.setFromServerId(fromServerId);
        builder.setToUserId(toUserId);
        return builder;
    }

    /**
     * 他人申请
     */
    public void listOtherApply(long playerId, int pageNo, int pageSize) {

    }

    /**
     * 检查申请状态
     */
    public void checkApplyState(long serverId, long userId, LionDanceProto.LionDanceCheckApplyStatusReqMsg req) {
        LionDanceProto.LionDanceCheckApplyStatusRespMsg.Builder respMsg = LionDanceProto.LionDanceCheckApplyStatusRespMsg.newBuilder();
        for (LionDanceProto.LionDanceUserApplyStateTemp stateTemp : req.getApplyList()) {
            LionDanceUserApplyData applyData = applyDataMap.get(stateTemp.getUserId());
            if(applyData != null){
                if(applyData.getStatus() == 0 && applyData.getApplyNo() == stateTemp.getApplyNo()){
                    LionDanceProto.LionDanceUserApplyStateTemp.Builder stateBuilder = LionDanceProto.LionDanceUserApplyStateTemp.newBuilder();
                    stateBuilder.setUserId(stateTemp.getUserId());
                    stateBuilder.setApplyNo(stateTemp.getApplyNo());
                    respMsg.addApply(stateBuilder);
                }
            }
        }
        respMsg.setRet(0);
        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_LION_DANCE_CHECK_APPLY_STATE, respMsg));
    }

    public void syncAllMakeProcess(long serverId) {
        LionDanceProto.CrossLionDanceSyncAllMakeNumMsg.Builder sync = LionDanceProto.CrossLionDanceSyncAllMakeNumMsg.newBuilder();
        sync.setActivityId(activityInfo.getActivityId());
        sync.setCount(activityData.getAllMakeNum());
        sync.setProcess((int)activityData.getAllProcess());
        MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_LION_DANCE_ALL_CONTRIBUTION_SYNC_FROM_CROSS, sync));
    }
}
